package com.tancw.viewacty;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.pdf.PdfDocument;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.material.tabs.TabLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/110499810
 */
public class MainActivity extends AppCompatActivity {

    private HashMap<String,JSONObject> chooseData = new HashMap();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        LinearLayout layout = findViewById(R.id.main);
        ViewCompat.setOnApplyWindowInsetsListener(layout, (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        initTab();
        //加载列表数据
        loadList();
        Log.i("main", "APP Start");
    }

    private void initTab() {
        TabLayout tab = findViewById(R.id.bottom_tab_layout);
        tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Log.d("tab", tab.getText() + ":" + tab.getPosition());
                int pos = tab.getPosition();
                loadTabPage(pos);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        tab.addTab(tab.newTab().setText("首页"));
        tab.addTab(tab.newTab().setText("新增"));
        tab.addTab(tab.newTab().setText("导出"));
    }

    private void loadTabPage(int pos) {
        switch (pos) {
            case 0:
              break;
            case 1:
                Intent intent1 = new Intent(MainActivity.this, RegActivity.class);
                startActivity(intent1);
                break;
            case 2:
                exportChoose();
                break;
        }
    }

    private void exportChoose() {
        if(chooseData.size() == 0){
            Toast.makeText(this, "请选择数据", Toast.LENGTH_LONG).show();
            return;
        }
        new AlertDialog.Builder(MainActivity.this).setTitle("确认导出选中的" + chooseData.size() + "项?")
                .setPositiveButton("确认", (dialog, which) -> {
                    //Toast.makeText(this, "导出成功", Toast.LENGTH_LONG).show();

                    Intent intent = new Intent(MainActivity.this, DownloadActivity.class);

                    JSONArray  datas =  new JSONArray();
                    for(JSONObject item : chooseData.values()){
                        datas.put(item.toString());
                    }
                    intent.putExtra("list", datas.toString());
                    startActivity(intent);

                }).setNegativeButton("取消", (dialog, which) -> {
                }).show();
    }



    public void loadList() {
        ListView listView = findViewById(R.id.list_view);
        List<JSONObject> datas = loadDatas();
        MyAdapter myAdapter = new MyAdapter(datas);
        listView.setAdapter(myAdapter);
    }

    private List<JSONObject> loadDatas() {
        List<JSONObject> datas = new ArrayList<>();
        List<String> txts = loadTxtFile();
        for (String name : txts) {
            JSONObject obj = null;
            try {
                obj = new JSONObject(loadText(name));
                obj.put("fileName", name);
                datas.add(obj);
            } catch (JSONException e) {

            }

        }
        return datas;
    }

    public List<String> loadTxtFile() {
        String[] data = fileList();
        ArrayList<String> txts = new ArrayList<>();
        for (int i = 0; i < data.length; i++) {
            if (data[i].endsWith("txt")) {
                txts.add(data[i]);
            }
        }
        Collections.reverse(txts);
        return txts;
    }

    public String loadText(String fileName) {
        FileInputStream fis = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            fis = openFileInput(fileName);
            reader = new BufferedReader(new InputStreamReader(fis));
            String str;
            while ((str = reader.readLine()) != null) {
                content.append(str);
            }
            Log.i("main", "加载内容:" + content);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return content.toString();
    }

    public class MyAdapter extends BaseAdapter {

        private List<JSONObject> datas;

        public MyAdapter(List<JSONObject> datas) {
            this.datas = datas;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(MainActivity.this, R.layout.item, null);
            buildItem(view, position);
            buildBtn(view, position);
            return view;
        }

        private void buildItem(View view, int position) {
            try {
                JSONObject data = datas.get(position);
                CheckBox itemCk = view.findViewById(R.id.itemCk);
                String filename = data.getString("fileName");
                itemCk.setText(filename);
                itemCk.setOnClickListener(v->{
                    if(itemCk.isChecked()){
                        chooseData.put(filename,data);
                        Log.d("选中","数据条数：" + chooseData.size());
                    }else{
                        chooseData.remove(filename);
                        Log.d("选中","取消选中，数据条数：" + chooseData.size());
                    }
                });
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }

        private void buildBtn(View view, int position) {
            Button button = view.findViewById(R.id.itemButton);
            button.setOnClickListener(v -> {
                Intent intent = new Intent(MainActivity.this, DetailActivity.class);
                JSONObject data = datas.get(position);
                try {
                    intent.putExtra("thing", data.getString("thing"));
                    intent.putExtra("user", data.getString("user"));
                    intent.putExtra("imgPaths", data.getString("imgPaths"));
                    intent.putExtra("fileName", data.getString("fileName"));
                    startActivity(intent);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
}